﻿using System;
using System.Windows;
using ImageControl.Common;

namespace ImageControl.Models
{
    public class ImageModel
    {
        public Point ImageTopLeft { get; private set; }

        public double OrientedWidth { get; private set; }

        public double OrientedHeight { get; private set; }

        public double Rotation { get; private set; }

        public Point TopLeft
        {
            get
            {
                double xFlipping = this.HasFlippingX ? this.Width : 0;
                double yFlipping = this.HasFlippingY ? this.Height : 0;

                return new Point(
                    this.ImageTopLeft.X - xFlipping,
                    this.ImageTopLeft.Y - yFlipping);
            }
        }

        public bool HasFlippingX
        {
            get
            {
                return this.OrientedWidth < 0;
            }
        }

        public bool HasFlippingY
        {
            get
            {
                return this.OrientedHeight < 0;
            }
        }

        public double Width
        {
            get
            {
                return Math.Abs(this.OrientedWidth);
            }
        }

        public double Height
        {
            get
            {
                return Math.Abs(this.OrientedHeight);
            }
        }

        public Point Center
        {
            get
            {
                return this.ImageTopLeft.Plus(new Point(this.OrientedWidth / 2, this.OrientedHeight / 2));
            }
        }

        public Point RotatedTopLeft
        {
            get
            {
                return this.ImageTopLeft.Rotate(this.Rotation, this.Center);
            }
        }

        public ImageModel(double orientedWidth, double orientedHeight, double rotation, Point imageTopLeft)
        {
            this.ImageTopLeft = imageTopLeft;
            this.OrientedWidth = orientedWidth;
            this.OrientedHeight = orientedHeight;
            this.Rotation = rotation;
        }

        public override bool Equals(object obj)
        {
            ImageModel other = obj as ImageModel;

            if (other == null)
            {
                return false;
            }

            return
                this.ImageTopLeft.Equals(other.ImageTopLeft) &&
                this.OrientedWidth.Equals(other.OrientedWidth) &&
                this.OrientedHeight.Equals(other.OrientedHeight) &&
                this.Rotation.Equals(other.Rotation);
        }

        public override int GetHashCode()
        {
            return
                this.ImageTopLeft.GetHashCode() ^
                this.OrientedWidth.GetHashCode() ^
                this.OrientedHeight.GetHashCode() ^
                this.Rotation.GetHashCode();
        }
    }
}
